#pragma once

#include "ui/input.hpp"
#include "display/interactive-object.h"

namespace tmlib {

    namespace display {

        /**
         *  @brief  
         */
        InteractiveObject::InteractiveObject()
            : _clickX(-1), _clickY(-1), _mouseOnFlag(false), _mouseDownFlag(false)
        {

        }


        /**
         *  @brief  
         */
        InteractiveObject::~InteractiveObject() {}


        /**
         *  @brief  
         */
        void InteractiveObject::update()
        {
            dispatchEvent(events::EventInfo::UPDATE);

            if (MouseInfoHolder::isCreate()) {
                Rectangle temp(finalX(), finalY(), _rect.width(), _rect.height());
#if 1
                if ( temp.contain(theMouseInfo.x(), theMouseInfo.y()) )
#else
                if ( _rect.contain(theMouseInfo.x(), theMouseInfo.y()) )
#endif
                {
                    _mouseOnFlag = true;
                    dispatchEvent(events::EventInfo::MOUSE_OVER);
                }
                else {
                    if (_mouseOnFlag == true) {
                        dispatchEvent(events::EventInfo::MOUSE_OUT);
                    }
                    _mouseOnFlag = false;
                }

                if (_mouseOnFlag == true) {
                    if (theMouseInfo.getState() == MouseInfo::STATE_DOWN) {
                        if (_mouseDownFlag == false) {
                            _clickX = theMouseInfo.x();
                            _clickY = theMouseInfo.y();
                        }
                        dispatchEvent(events::EventInfo::MOUSE_DOWN);
                        _mouseDownFlag = true;
                    }
                }

                if (theMouseInfo.getState() == MouseInfo::STATE_UP) {
                    if (_mouseDownFlag == true) {
                        dispatchEvent(events::EventInfo::MOUSE_UP);
                        _mouseDownFlag = false;

                        if (abs(_clickX-theMouseInfo.x()) <= 4 && abs(_clickY-theMouseInfo.y()) <= 4 ) {
                            // click
                            dispatchEvent(events::EventInfo::CLICK);
                            _clickX = -1;
                            _clickY = -1;
                        }
                    }
                }

            }

        }

    }

}
